package org.ling.xuan.action;

import cn.hutool.core.util.StrUtil;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.ling.xuan.util.LoggerUtil;
import org.ling.xuan.util.LxStrUtil;

import java.nio.charset.StandardCharsets;

public class LxConsoleUpdAction extends AnAction {

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        VirtualFile file = e.getDataContext().getData(CommonDataKeys.VIRTUAL_FILE);
        if (project != null && file != null) {
            String content = "";
            try {
                content = new String(file.contentsToByteArray(),StandardCharsets.UTF_8);
            } catch (Exception ex) {
                content = "";
            }
            if (StrUtil.isNotBlank(content)) {
                content = content.replace("\r\n", "\n");
                LoggerUtil.log(project, LxStrUtil.convertUpdXmlToUpd(content));
            } else {
                LoggerUtil.log(project, "get content failed");
            }
        }
    }

    @Override
    public void update(AnActionEvent e) {
        boolean flag = false;
        DataContext dataContext = e.getDataContext();
        VirtualFile virtualFile = dataContext.getData(CommonDataKeys.VIRTUAL_FILE);
        // 检查当前文件是否为有效文件
        if (virtualFile != null && virtualFile.isValid()) {
            // 获取当前文件的路径
            String filePath = virtualFile.getPath();
            flag = filePath.endsWith("-upd.xml");
        }
        e.getPresentation().setEnabledAndVisible(flag);
    }
}
